package com.jrx.anytxn.param.controller.aviator;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnRuntimeException;
import com.jrx.anytxn.param.dto.aviator.RuleMatchReq;
import com.jrx.anytxn.param.service.aviator.IAviatorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @Author: haopu.zheng
 * @Description: 执行规则
 * @Date: 2019/8/2
 **/
@Api(tags = "匹配规则api")
@RestController
@RequestMapping("/param")
public class ExecuteRuleController {

    private static final Logger logger = LoggerFactory.getLogger(ExecuteRuleController.class);
    @Autowired
    private IAviatorService aviatorService;

    @ApiOperation(value = "执行匹配规则")
    @PostMapping(value = "/rules/executing")
    public TxnRespResult executeRule(@RequestBody String json) {
        logger.info("match rule start");
        TxnRespResult result = new TxnRespResult<>();
        ObjectMapper mapper = new ObjectMapper();
        RuleMatchReq ruleMatchDTO;
        try {
            ruleMatchDTO = mapper.readValue(json, RuleMatchReq.class);
        } catch (IOException e) {
            result.setCode(TxnRespCode.ERROR.getCode());
            result.setMessage(TxnRespCode.ERROR.getMsg());
            return result;
        }

        if (StringUtils.isEmpty(ruleMatchDTO.getRuleType()) || MapUtils.isEmpty(ruleMatchDTO.getRuleParam())) {
            result.setCode(TxnRespCode.NOT_EMPTY.getCode());
            result.setMessage(TxnRespCode.NOT_EMPTY.getMsg());
            return result;
        }

        try {
            String executeResult = aviatorService.executeRule(ruleMatchDTO);
            result.setData(executeResult);
        } catch (TxnRuntimeException e) {
            result.setCode(e.getErrCode());
            result.setMessage(e.getErrMsg());
            logger.error(e.getMessage(), e);
        }
        logger.info("match rule end");
        return result;
    }

}

